package com.inzone.fram.gray.config;

import com.inzone.fram.gray.common.rule.MatchingContext;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 给RestTemple添加拦截器传递灰度头
 *
 * @author 丁常磊
 * @date 2021/10/15 19:19
 */

@ConditionalOnClass({
        RestTemplate.class,
        LoadBalanced.class
})
@ConditionalOnBean({
        RestTemplate.class,
})
@Configuration
public class MatchingInitRestTemplateConfig implements InitializingBean {

    @LoadBalanced
    @Autowired(required = false)
    private RestTemplate restTemplate;


    @Override
    public void afterPropertiesSet() throws Exception {

        if (restTemplate != null) {
            List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();

            interceptors.add((request, body, execution) -> {
                if (MatchingContext.isInitialized()) {
                    MatchingContext current = MatchingContext.current();
                    String tagsText = current.getTagsText();
                    if (tagsText != null) {
                        request.getHeaders().set(MatchingContext.GRAY_HEADER_TAGS, tagsText);
                    }

                    String groupsText = current.getGroupsText();
                    if (groupsText != null) {
                        request.getHeaders().set(MatchingContext.GRAY_HEADER_GROUPS, groupsText);
                    }
                }
                return execution.execute(request, body);
            });

        }

    }

}
